package com.colortea.action.frontstage.membercenter;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.colortea.action.backstage.base.BaseTAction;
import com.colortea.action.backstage.base.DataCollectionTAction;
import com.colortea.action.backstage.utils.BaseTools;
import com.colortea.action.backstage.utils.order.AllOrderState;
import com.colortea.action.backstage.utils.statickey.FreeMarkervariable;
import com.colortea.action.backstage.utils.statickey.StaticKey;
import com.colortea.action.frontstage.order.OrderObj;
import com.colortea.action.frontstage.utils.Arith;
import com.colortea.action.frontstage.utils.PageModel;
import com.colortea.action.frontstage.utils.enums.FrontEnums.CartGoodsState;
import com.colortea.action.frontstage.utils.enums.FrontEnums.OrderCreateTag;
import com.colortea.entity.CartT;
import com.colortea.entity.GoodsT;
import com.colortea.entity.LogisticsBusinessT;
import com.colortea.entity.LogisticsbusinessareaT;
import com.colortea.entity.MemberT;
import com.colortea.entity.OrderT;
import com.colortea.entity.PaymentM;
import com.colortea.service.CartTService;
import com.colortea.service.DeliverAddressTService;
import com.colortea.service.GoodsTService;
import com.colortea.service.LogisticsBAreaTService;
import com.colortea.service.LogisticsBTService;
import com.colortea.service.OrderBaseProcessTService;
import com.colortea.service.OrderTService;
import com.colortea.service.PaymentMService;
import com.colortea.service.ShippingAddressTService;
import com.opensymphony.xwork2.ActionContext;

@ParentPackage("colortea")
@Namespace("/mcenter")
@InterceptorRefs({ @InterceptorRef("defaultStack") })
public class OrderAction extends BaseTAction{

	@Resource
	private DataCollectionTAction dataCollectionTAction;
	@Resource
	private OrderTService orderTService;
	@Resource
	private DeliverAddressTService deliverAddressTService;
	@Resource
	private CartTService cartTService;
	@Resource
	private LogisticsBTService logisticsBTService;
	@Resource
	private PaymentMService paymentMService;
	@Resource
	private LogisticsBAreaTService logisticsBAreaTService;
	@Resource
	private ShippingAddressTService shippingAddressTService;

	@Resource
	private OrderBaseProcessTService orderBaseProcessTService;
	@Resource
	private GoodsTService goodsTService;

	@Action(value = "gomyorderlist", results = { 
			@Result(name = "success",type="freemarker",location = "/WEB-INF/theme/default/shop/myorder.ftl"),
			@Result(name = "gologin",type="freemarker",location = "/WEB-INF/theme/default/shop/login.ftl"),
	})
	public String gomyorderlist(){
		dataCollectionTAction.putBaseInfoToContext();
		MemberT memberT = (MemberT) ActionContext.getContext().getSession().get(StaticKey.MEMBER_SESSION_KEY);
		if (memberT != null) {
			//获取最近的订单信息
			this.findAllUserOrderOn(memberT.getId());
			
			return SUCCESS;
		}
		return "gologin";
		
		
	}
	/**
	 * 获取用户未处理的订单只获取前300条
	 */
	public void findAllUserOrderOn(String memberid){
		int currentPage=1;
		int lineSize=100000;
		Criterion criterion=Restrictions.and(Restrictions.ne("orderstate", AllOrderState.ORDERSTATE_EIGHT_NUM)).add(Restrictions.eq("memberid", memberid));
		List<OrderT>list=this.orderTService.findByCriteriaByPage(OrderT.class, criterion, Order.desc("purchasetime"), currentPage, lineSize);
		String action=BaseTools.getBasePath()+"/mcenter/gomyorderlist.action?";
		ActionContext.getContext().put("actionlink", action);
		ActionContext.getContext().put("sign", "disstatic");
		ActionContext.getContext().put(FreeMarkervariable.MEMBERORDERON,list);
	}
	
	
	@Action(value = "initOrderag", results = {
			@Result(name = "success", type = "freemarker", location = "/WEB-INF/theme/default/shop/orderag.ftl"),
			@Result(name = "input", type = "chain", location = "gologin") })
	public String initOrderAg(){
		this.dataCollectionTAction.putBaseInfoToContext();
		MemberT memberT = (MemberT) ActionContext.getContext().getSession()
				.get(StaticKey.MEMBER_SESSION_KEY);
		if (memberT != null) {
			// 获取用户收获地址信息
			ActionContext.getContext().put(FreeMarkervariable.DELIVERADDRESS,
					orderBaseProcessTService.getMemberDeliverAddress(memberT));
			// 获取物流商 需要设定一个默认物流商来计算运费
			ActionContext.getContext().put(
					FreeMarkervariable.LOGISTICS,
					orderBaseProcessTService
							.getLogisticstsBusiness(StaticKey.ONE));
			// 获取支付方式
			ActionContext.getContext().put(FreeMarkervariable.PAYMENTS,
					orderBaseProcessTService.getPaymentM(StaticKey.ONE));
			if (StringUtils.isNotBlank(this.getGoodsstr())) {
				// 如果传递了goodsstr说明是直接购买，所以直接购买必须传递goodsstr，并且不会被加入购物车,直接从商品表取
				GoodsT goods = this.goodsTService.findByPK(GoodsT.class,
						this.getGoodsstr());
				if (goods != null) {
					ActionContext.getContext().put(FreeMarkervariable.GOODS,
							goods);
					getMemberGoodsInfo(goods);
				}
				// 不从购物车取出商品计算
				ActionContext.getContext().put(
						FreeMarkervariable.ISGOODSFROMCART, StaticKey.ZERO);
				
			} else {
				// 没有传递goodsstr说明是加入购物车后，下单，商品数据从cart中选择
				List<CartT> list = orderBaseProcessTService.getMemberCart(
						memberT.getId(),
						CartGoodsState.NEWADDTOCART_NUM.getState(),
						OrderCreateTag.NORMAL.getState());
				ActionContext.getContext().put(FreeMarkervariable.MEMBERCART,
						list);
				// 从购物车取出商品计算
				ActionContext.getContext().put(
						FreeMarkervariable.ISGOODSFROMCART, StaticKey.ONE);
				// 计算购物车信息
				getMemberCartInfo(list);

			}
			// 获取总价
			ActionContext.getContext()
					.put(FreeMarkervariable.TOTALPRICE, total);
			// 获取总积分
			ActionContext.getContext().put(FreeMarkervariable.TOTALPOINTS,
					totalpoints);
			// 获取购物车ID
			// cartid＝＝0表示商品不是从购物车计算来的
			//ActionContext.getContext().put(FreeMarkervariable.CARTID, cartid);
			// 获取购物车中商品ID串
			ActionContext.getContext().put(FreeMarkervariable.CARTGOODSID,
					cartgoodsid);
			// 获取购物车中商品名称串
//			ActionContext.getContext().put(FreeMarkervariable.CARTGOODSNAME,
//					cartgoodsname);
			// 获取购物车中商品总数
			ActionContext.getContext().put(FreeMarkervariable.CARTNEEDQUANTITY,
					cartneedquantity);
			// 运费
			ActionContext.getContext().put(FreeMarkervariable.FREIGHT,
					getLogisticsPrice());
			// 获取总金额+运费
			Double totalfreight = this.getTotal() + this.getFreight();
			ActionContext.getContext().put(FreeMarkervariable.TOTALFREIGHT,
					totalfreight);
			//获取用户发票抬头信息
			ActionContext.getContext().put(FreeMarkervariable.INVOICE, orderBaseProcessTService.getMyInvoice(memberT.getId()));
			
			OrderT orderT = orderTService.findByPK(OrderT.class, this.getConfirmorderid());
			PaymentM m = paymentMService.findByPK(PaymentM.class, orderT.getPaymentid());
			orderObj = new OrderObj();
			if("wyzf".equals(m.getPaymentCode())){
				orderObj.setDefaultbank(orderT.getDefaultbank()); // 银行简码
			}
			orderObj.setPaycode(m.getPaymentCode()); // 支付方式
			orderObj.setOut_trade_no(orderT.getOrderid()); // 订单号
			orderObj.setSubject(orderT.getOrdername()); // 商品名称
			orderObj.setTotal_fee(String.valueOf(orderT.getAmount())); // 金额
			return SUCCESS;
		}else{
			return INPUT;
		}

	}
	
	
	/**
	 * 计算运费
	 */
	private double getLogisticsPrice() {
		// Double temptotal = this.getTotal();
		Double freight = 5.0;
		List<LogisticsBusinessT> lblist = orderBaseProcessTService.getDefaultLogisticsBusinessT(StaticKey.ONE);
		if (lblist != null && lblist.size() > 0) {
			List<LogisticsbusinessareaT> list = orderBaseProcessTService.getDefaultLogisticsbusinessareaT(lblist.get(0).getLogisticsid());
			if (list != null) {
				Double tempfreight = 0.0;
				int tempy = 0;
				for (Iterator it = list.iterator(); it.hasNext();) {
					// LogisticsbusinessareaT lbt = (LogisticsbusinessareaT)
					// it.next();
					// if (this.getTotal() > lbt.getNeedcostmin() &&
					// this.getTotal() < lbt.getNeedcostmax() &&
					// this.getTotalweight() < lbt.getOvervalue()) {
					// tempfreight = lbt.getNormalcost();
					// tempy = (int) (this.getTotalweight() / 1000);
					// } else if (this.getTotal() > lbt.getNeedcostmin() &&
					// this.getTotal() < lbt.getNeedcostmax() &&
					// this.getTotalweight() < lbt.getOvervalue()) {
					// tempfreight = 0.0;
					// tempy = (int) (this.getTotalweight() / 1000);
					// } else {
					// tempfreight = 0.0;
					// tempy = (int) (this.getTotalweight() / 1000);
					// }
				}
				freight = tempfreight + tempy;
				this.setFreight(freight);
			}
		}
		return freight;

	}
	/**
	 * 获取购物车中的商品作为订单商品处理
	 * 
	 * 
	 */
	public void getMemberCartInfo(List<CartT> list) {
		if (!list.isEmpty()) {
			this.setTotal(0.0);
			this.setTotalweight(0.0);
			this.setTotalpoints(0.0);
			this.setCartgoodsname(StaticKey.EMPTY);
			this.setCartgoodsid(StaticKey.EMPTY);
			this.setCartneedquantity(0);
			for (Iterator<CartT> it = list.iterator(); it.hasNext();) {
				CartT ct = (CartT) it.next();
				total = Arith.add(total, Arith.mul(ct.getFavorable()
						.doubleValue(), Double.parseDouble(String.valueOf(ct
						.getNeedquantity()))));
				if (ct.getWeight() != null&&ct.getWeight().length()>0) {
					totalweight = Arith
							.add(totalweight, Arith.mul(Double.parseDouble(ct
									.getWeight()), Double.parseDouble(String
									.valueOf(ct.getNeedquantity()))));
				}
				totalpoints = Arith.add(totalpoints, Arith.mul(ct.getPoints()
						.doubleValue(), Double.parseDouble(String.valueOf(ct
						.getNeedquantity()))));
				cartgoodsname = ct.getGoodsname();
				cartgoodsid += ct.getGoodsid() + ",";
				cartneedquantity += ct.getNeedquantity();
				//cartid = ct.getCartid();// 获取购物车中的cartid表示同一个cartid即在同一个订单中
				ordermainpicture = ct.getPicture();// 用于订单界面中显示一个主图
			}
		}
	}

	private void getMemberGoodsInfo(GoodsT g){
		if(g!=null){
			this.setTotal(0.0);
			this.setTotalweight(0.0);
			this.setTotalpoints(0.0);
			this.setCartgoodsname(StaticKey.EMPTY);
			this.setCartgoodsid(StaticKey.EMPTY);
			this.setCartneedquantity(0);
			total=g.getMemberprice().doubleValue();
			if(StringUtils.isNotBlank(g.getWeight())){
				totalweight=Double.valueOf(g.getWeight().toString());
			}
			totalpoints=g.getPoints().doubleValue();
			cartgoodsname=g.getGoodsname();
			cartgoodsid=g.getGoodsid();
			cartneedquantity=1;
			String strs[]=StringUtils.split(g.getPictureurl(), StaticKey.SPLITDOT);
			if(strs.length>0){
				ordermainpicture=strs[0];
			}
		
		}
	}

	/**
	 * 确认订单收货
	 * @return
	 */
	@Action(value = "confirmOrderReceive", 
			results = { @Result(name = "success", type = "chain", location = "gomyorderlist"), 
			@Result(name = "gologin",type="freemarker",location = "/WEB-INF/theme/default/shop/login.ftl"),
	})
	public String confirmOrderReceive(){
		this.dataCollectionTAction.putBaseInfoToContext();
		MemberT memberT = (MemberT) ActionContext.getContext().getSession()
				.get(StaticKey.MEMBER_SESSION_KEY);
		if (memberT != null) {
			if(StringUtils.isNotBlank(this.getConfirmorderid())){
				OrderT order=this.orderTService.findByPK(OrderT.class, this.getConfirmorderid());
				if(order!=null){
					order.setOrderstate(AllOrderState.ORDERSTATE_SIX_NUM);//用户已经确认收货
					this.orderTService.update(order);
					return SUCCESS;
				}
			}
		}
		return "gologin";
	}
	
	/**
	 * 根据ID查询订单详情
	 * @return
	 */
	@Action(value = "findOrderTById", results = { @Result(name = "json", type = "json") })
	public String findOrderTById(){
		OrderT orderT = orderTService.findByPK(OrderT.class, this.getConfirmorderid());
		PaymentM m = paymentMService.findByPK(PaymentM.class, orderT.getPaymentid());
		orderObj = new OrderObj();
		if("wyzf".equals(m.getPaymentCode())){
			orderObj.setDefaultbank(orderT.getDefaultbank()); // 银行简码
		}
		orderObj.setPaycode(m.getPaymentCode()); // 支付方式
		orderObj.setOut_trade_no(orderT.getOrderid()); // 订单号
		orderObj.setSubject(orderT.getOrdername()); // 商品名称
		orderObj.setTotal_fee(String.valueOf(orderT.getAmount())); // 金额
		return JSON;
	}
	
	/**
	 * 购买的商品id
	 */
	private String goodsstr;
	private Double total;// 会员总价
	private Double totalweight;
	private Double totalpoints;
	private String cartgoodsname="";
	private String cartgoodsid="";
	private int cartneedquantity;
	private String ordermainpicture="";// 订单中显示的主图片
	private Double freight;
	private OrderObj orderObj;
	
	private String confirmorderid;//确认收货的订单id

	
	public String getConfirmorderid() {
		return confirmorderid;
	}
	public void setConfirmorderid(String confirmorderid) {
		this.confirmorderid = confirmorderid;
	}
	public String getGoodsstr() {
		return goodsstr;
	}
	public void setGoodsstr(String goodsstr) {
		this.goodsstr = goodsstr;
	}
	public Double getTotalweight() {
		return totalweight;
	}
	public void setTotalweight(Double totalweight) {
		this.totalweight = totalweight;
	}
	public Double getTotalpoints() {
		return totalpoints;
	}
	public void setTotalpoints(Double totalpoints) {
		this.totalpoints = totalpoints;
	}
	public String getCartgoodsname() {
		return cartgoodsname;
	}
	public void setCartgoodsname(String cartgoodsname) {
		this.cartgoodsname = cartgoodsname;
	}
	public String getCartgoodsid() {
		return cartgoodsid;
	}
	public void setCartgoodsid(String cartgoodsid) {
		this.cartgoodsid = cartgoodsid;
	}
	public int getCartneedquantity() {
		return cartneedquantity;
	}
	public void setCartneedquantity(int cartneedquantity) {
		this.cartneedquantity = cartneedquantity;
	}
	public String getOrdermainpicture() {
		return ordermainpicture;
	}
	public void setOrdermainpicture(String ordermainpicture) {
		this.ordermainpicture = ordermainpicture;
	}
	public Double getFreight() {
		return freight;
	}
	public void setFreight(Double freight) {
		this.freight = freight;
	}
	public void setTotal(Double total) {
		this.total = total;
	}
	public Double getTotal() {
		return total;
	}
	public OrderObj getOrderObj() {
		return orderObj;
	}
	public void setOrderObj(OrderObj orderObj) {
		this.orderObj = orderObj;
	}
	
}
